import { computed, onMounted, onUnmounted, ref } from 'vue';

import { useDark, usePreferredDark } from '@vueuse/core';

/**
 * 主题管理组合式函数
 * 提供当前主题状态和主题切换功能
 */
export function useTheme() {
  /* 使用vueuse提供的暗色主题检测 */
  const isDark = useDark();
  const prefersDark = usePreferredDark();

  /* 是否跟随系统主题 */
  const followSystem = ref(true);

  /* 监听系统主题变化的媒体查询 */
  let mediaQuery: MediaQueryList | null = null;
  let mediaQueryListener: ((e: MediaQueryListEvent) => void) | null = null;

  /* 计算当前主题 */
  const currentTheme = computed(() => (isDark.value ? 'dark' : 'light'));

  /* 主题类名 */
  const themeClass = computed(() => ({
    dark: isDark.value,
    light: !isDark.value,
  }));

  /* 切换主题 */
  const toggleTheme = () => {
    if (followSystem.value) {
      /* 如果之前是跟随系统，切换为手动模式 */
      followSystem.value = false;
    }
    isDark.value = !isDark.value;
  };

  /* 设置为暗色主题 */
  const setDarkTheme = () => {
    followSystem.value = false;
    isDark.value = true;
  };

  /* 设置为亮色主题 */
  const setLightTheme = () => {
    followSystem.value = false;
    isDark.value = false;
  };

  /* 设置跟随系统主题 */
  const setFollowSystem = () => {
    followSystem.value = true;
    isDark.value = prefersDark.value;
  };

  /* 初始化媒体查询监听 */
  onMounted(() => {
    /* 监听系统主题变化 */
    mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
    mediaQueryListener = (e: MediaQueryListEvent) => {
      if (followSystem.value) {
        isDark.value = e.matches;
      }
    };

    mediaQuery.addEventListener('change', mediaQueryListener);
  });

  /* 清理媒体查询监听 */
  onUnmounted(() => {
    if (mediaQuery && mediaQueryListener) {
      mediaQuery.removeEventListener('change', mediaQueryListener);
      mediaQuery = null;
      mediaQueryListener = null;
    }
  });

  return {
    isDark,
    currentTheme,
    themeClass,
    followSystem,
    toggleTheme,
    setDarkTheme,
    setLightTheme,
    setFollowSystem,
  };
}
